
    var form = layui.form, table = layui.table, $ = layui.jquery, id = getQueryVariable("id");
    var productList=[];//产品列表
    var peijianList=[];//配件列表
    var feiyong=[];//费用
    var fujian=[];//附件
    var fpzje=getAllRolesByCurr("shipmentplan_newupshipmentplan");//判断是否有此角色
    $(".customerLevelCodeHin").hide();//隐藏客户等级编码
    var ywbqx=getAllRolesByCurr("shipmentplan_newupshipmentplan_ywb");//判断是否有此角色
    $('#editor-form').find('input,textarea,select').attr('disabled',true);
    //表单初始值，修改时调用
  /*  if (id != "") {
        form.val("editor-form", {
            "contact": "进入查看明细",
        })
    }*/
    getContainerModel();//获取货柜型号
    //下拉框
    getlxandlevel();
    ////获取公司、客户名称
    setPullMenu();
    queryByid(id);
    getProdcuInfo();//获取产品列表
    getfeiyong();//获取费用
    getfujian();//获取文件附件
  //  form.render();

    let isContainsRoleShipPlan=false;
    getIsContainsRoleShipPlan();
    if (!isContainsRoleShipPlan){
        document.getElementById("logLi").style.display = "none";
    }

//--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid'
        ,data:productList,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true, fixed: true, totalRowText: '合计'},
            {field: 'img', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'purchaseNo', width: 120, title: '采购单号'},
            {field: 'customerContractNo', width: 120, title: '客户合同号' },
            {field: 'exportContractNo', width: 120, title: '外销合同号' },
            {field: 'productNo', width: 120, title: '产品编码'},//, templet:'#productcodeselect'
            {field: 'specNo', width: 120, title: '规格编码' },
            {field: 'normExplain', width: 120, title: '规格说明' },
            {field: 'customerContractNo', width: 120, title: '客户货号' },
            {field: 'chineseName', width: 120, title: '中文名称' },
            {field: 'englishName', width: 120, title: '英文名称'},
            {field: 'chineseDesc', width: 120, title: '中文描述' },
            {field: 'englishDesc', width: 120, title: '英文描述' },
            {field: 'amount', width: 100, title: '数量' ,
                templet: function(d){
                    let amount = d.amount?d.amount:0;
                    return Number(amount).toFixed(0)
                },totalRow: true
            },
            {field: 'unit', width: 120, title: '单位' },//, templet: '#unitselect'
            {field: 'price', width: 80, title: '单价' ,
                templet: function(d){
                    let price = d.price?d.price:0;
                    return Number(price)
                }
            },
            {field: 'priceSubtotal', width: 120, title: '金额小计' ,
                templet: function(d){
                    let priceSubtotal = d.priceSubtotal?d.priceSubtotal:0;
                    return Number(priceSubtotal).toFixed(2)
                },totalRow: true
            },
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码'},
            {field: 'colour', width: 120, title: '颜色' },
            {field: 'grossWeight', width: 120, title: '毛重' ,
                templet: function(d){
                    let grossWeight = d.grossWeight?d.grossWeight:0;
                    return Number(grossWeight).toFixed(2)
                }
            },
            {field: 'grossSubtotal', width: 120, title: '毛重小计' ,
                templet: function(d){
                    let grossSubtotal = d.grossSubtotal?d.grossSubtotal:0;
                    return Number(grossSubtotal).toFixed(2)
                }
            },
            {field: 'netWeight', width: 120, title: '净重',
                templet: function(d){
                    let netWeight = d.netWeight?d.netWeight:0;
                    return Number(netWeight).toFixed(2)
                }
            },
            {field: 'netSubtotal', width: 120, title: '净重小计' ,
                templet: function(d){
                    let netSubtotal = d.netSubtotal?d.netSubtotal:0;
                    return Number(netSubtotal).toFixed(4)
                }
            },
            {field: 'volume', width: 120, title: '体积' ,
                templet: function(d){
                    let volume = d.volume?d.volume:0;
                    return Number(volume).toFixed(2)
                }
            },
            {field: 'trayNumber', width: 120, title: '托数' ,
                templet: function(d){
                    let trayNumber = d.trayNumber?d.trayNumber:0;
                    return Number(trayNumber).toFixed(2)
                }
            },
            {field: 'trayCapacity', width: 120, title: '每托量' ,
                templet: function(d){
                    let trayCapacity = d.trayCapacity?d.trayCapacity:0;
                    return Number(trayCapacity).toFixed(2)
                }
            },
            {field: 'numberOfPiece', width: 120, title: '箱数' ,
                templet: function(d){
                    let numberOfPiece = d.numberOfPiece?d.numberOfPiece:0;
                    return Number(numberOfPiece).toFixed(2)
                }
            },
            {field: 'qty', width: 120, title: '每箱数量' ,
                templet: function(d){
                    let qty = d.qty?d.qty:0;
                    return Number(qty).toFixed(2)
                }
            },
            {field: 'payTime', width: 120, title: '付款账期' },
            {field: 'costPrice', width: 120, title: '成本单价' ,
                templet: function(d){
                    let costPrice = d.costPrice?d.costPrice:0;
                    return Number(costPrice).toFixed(6)
                }
            },
            {field: 'costPriceSubtotal', width: 120, title: '成本小计' ,
                templet: function(d){
                    let costPriceSubtotal = d.costPriceSubtotal?d.costPriceSubtotal:0;
                    return Number(costPriceSubtotal).toFixed(2)
                }
            },
            {field: 'wholeCostPrice', width: 120, title: '成品成本' ,
                templet: function(d){
                    let wholeCostPrice = d.wholeCostPrice?d.wholeCostPrice:0;
                    return Number(wholeCostPrice).toFixed(6)
                }
            },
            {field: 'accessoryCostPrice', width: 120, title: '配件成本' ,
                templet: function(d){
                    let accessoryCostPrice = d.accessoryCostPrice?d.accessoryCostPrice:0;
                    return Number(accessoryCostPrice).toFixed(6)
                }
            },
            {field: 'supplierName', width: 120, title: '供应商' },

            {field:'outPackLength', title:'外包装长', width: 120 },
            {field:'outPackWidth', title:'外包装宽', width: 120 },
            {field:'outPackHeight', title:'外包装高', width: 120 },
            {field:'outPackSize', title:'外包装尺寸', width: 120 },
            // {field:'outPackNum', title:'外包装单位', width: 120 },
            {field:'remark', title:'备注', width: 120 },
        ]],
       // page: true,
        limit:Number.MAX_VALUE
        ,height: 380
        , done: function (res, curr, count) {
            if(fpzje){
                $("[data-field='priceSubtotal']").css("display", "none");
                $("[data-field='price']").css("display", "none");

            }
            if(ywbqx){
                $("[data-field='costPrice']").css("display", "none");
                $("[data-field='costPriceSubtotal']").css("display", "none");
                $("[data-field='wholeCostPrice']").css("display", "none");
                $("[data-field='accessoryCostPrice']").css("display", "none");
                $("[data-field='supplierName']").css("display", "none");

            }
            hoverOpenImg();//显示大图
        }
    });
    //监听行单击事件
    table.on('row(storageproductstable)', function(obj){
        $("#hidden").show();

        var pjData=[];
        for(var i=0;i<peijianList.length;i++){
            if(obj.data.productId==peijianList[i].productId){
                pjData.push(peijianList[i].changeList);
            }
        }
        if(pjData.length==0){
            pjData=[]
        }else{
            pjData=pjData[0];
        }
        table.render({
            elem: '#productsaselect'
            ,data:pjData//data2
            ,toolbar: '#productsatoolbar'
            ,cols: [[
                {checkbox: true, fixed: true}
                ,{field: 'productNo', title: '产品编码'}
                ,{field: 'specNo', title: '规格编码' }
                ,{field:'proportionFinishedProducts', title:'成品比例'}
                ,{field:'partsFinishedProducts', title:'配件比例' }
                ,{field:'amount', title:'配件数量',
                    templet: function(d){
                        let amount = d.amount?d.amount:0;
                        return Number(amount).toFixed(2)
                    }
                }
                ,{field: 'costPrice', width: 120, title: '成本单价'  ,
                    templet: function(d){
                        let costPrice = d.costPrice?d.costPrice:0;
                        return Number(costPrice).toFixed(6)
                    }
                }
                ,{field: 'costPriceSubtotal', width: 120, title: '成本小计'  ,
                    templet: function(d){
                        let costPriceSubtotal = d.costPriceSubtotal?d.costPriceSubtotal:0;
                        return Number(costPriceSubtotal).toFixed(2)
                    }
                }
                ,{field: 'purchaseNo', width: 120, title: '采购单号' }
                ,{field: 'supplierName', width: 120, title: '供应商' }
                ,{field:'chineseName', title:'中文名称' }
                ,{field:'englishName', title:'英文名称' }
                ,{field:'grossWeight', title:'毛重' , edit:'text' ,
                    templet: function(d){
                        let grossWeight = d.grossWeight?d.grossWeight:0;
                        return Number(grossWeight).toFixed(2)
                    }
                }
                ,{field:'netWeight', title:'净重' , edit:'text' ,
                    templet: function(d){
                        let netWeight = d.netWeight?d.netWeight:0;
                        return Number(netWeight).toFixed(2)
                    }
                }
                ,{field:'volume', title:'体积' , edit:'text' ,
                    templet: function(d){
                        let volume = d.volume?d.volume:0;
                        return Number(volume).toFixed(2)
                    }
                }
            ]]
            ,id: 'productsatableid'
            //,page: false
            ,limit:Number.MAX_VALUE
            ,height:300
            , done: function (res, curr, count) {

                if(ywbqx){
                    $("[data-field='costPrice']").css("display", "none");
                    $("[data-field='costPriceSubtotal']").css("display", "none");
                    $("[data-field='supplierName']").css("display", "none");

                }


            }
        });
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }
    let costType = getdictionary(5,19);  //费用类型
//---费用
    table.render({
        elem: '#cost'
        ,url:"shipmentPlan/selectCostBySpId"
        ,where: {
           "shipmentPlanId": id//出运计划id
        }
        ,method:"get"
        , toolbar: '#costtoolbar'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'costType', title: '费用类型', templet:function(d){
                for (let i in costType) {
                    if(d.costType==costType[i].code)return costType[i].name
                }
                }}
            , {field: 'costMoney', title: '金额'}
            , {field: 'contractNo', title: '销售合同号'}
            , {field: 'costDesc', title: '备注说明' }
        ]]
        , id: 'costtableid'
        , height: 380
        , page: true
    });
//---附件
    table.render({
        elem: '#attachment'
        ,url:"shipmentPlan/selectFileBySpId"
        ,where: {
            "shipmentPlanId": id//出运计划id
        }
        ,method:"get"
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true,event: "fileName"}
            , {field: 'fileUploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    table.on('tool(attachmenttable)', function (obj) {

       // downFileLoad(obj.data.fileUrl);

        var data = obj.data;
        if (obj.event === 'download') { //下载
            downFileLoadNew(data.fileName,data.fileUrl);

        } else if(obj.event === 'fileName'){//点击名称，在线预览
            onLineFile(obj.data.fileUrl);
        }
    });

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        ,url:"shipmentPlan/getLogByPage"
        ,where: {
            "shipmentPlanId": id
        }
        ,method:"get"
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'opname', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //费用 获取数据
    function getfeiyong() {
        $.ajax({
            type : 'GET',
            //  url : 'resource/getTree',
            url:'shipmentPlan/selectCostBySpId',
            data:{"shipmentPlanId":id},
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){

                    feiyong=da.data;
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
        table.reload('costtableid',{data : feiyong});

    }

    function queryByid(da) {
        $.ajax({
            type : 'GET',
            //  url : 'resource/getTre,
            data:{"id":da},
            url:'shipmentPlan/selectByKey',
            dataType:"json",
            /*  contentType: 'application/json',*/
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    initData(da.data);
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
    }
    function  initData(data) {
        form.val("editor-form", {
            "id": data.id,
            "customerCode": data.customerName,//客户名称
            "contactPerson": data.contactPerson,//联系人
            "shipmentNo": data.shipmentNo,//计划编号
            "shipmentDate": data.shipmentDate,//出运日期
            "currency": data.currency,//币种
            "usdRate": data.usdRate,//美元汇率
            "rmbRate": data.rmbRate,//人民币汇率
            "startPlace": data.startPlace,//起运地
            "endPlace": data.endPlace,//目的地
            "targetCountry": data.targetCountry,//运抵国家
            "transhipment": data.transhipment,//转船运输
            "transMode": data.transMode,//运输方式
            "paymentTerm": data.paymentTerm,//收款类型
            "priceTerm": data.priceTerm,//价格术语
            "invoiceAmount": data.invoiceAmount,//发票总额
            "makeTime": data.makeTime,//制单日期
            "salesContractNo": data.salesContractNo,//销售合同号
            "customerContractNo": data.customerContractNo,//客户合同号
            "salesmanCode": data.salesmanCode,//业务员
            "businessMode": data.businessMode,//业务模式
            "proFinishDate": data.proFinishDate,//货好日期
            "brand": data.brand,//品牌
            "stock": data.stock,//仓库
            "boxType": data.boxType,//箱型
            "payDay": data.payDay,//客户账期
            "declareCompany": data.declareCompany,//报关抬头
            "companyCode": data.companyCode,//签约公司
            "bankCode": data.bankCode,//银行
            "executorName":data.executorName,
            "customerLevelName":data.customerLevelName,//客户等级名称
            "customerLevelCode":data.customerLevelCode,//客户等级编码
            "containerNum":data.containerNum,//货柜数量
            "containerTypeCode":data.containerTypeCode,//货柜型号编码
            "containerType":data.containerType,//货柜型号
            "whetherCreditGuarantee":data.whetherCreditGuarantee,//是否走信保订单(0:否 1:是)
            "creditGuaranteeAmount":data.creditGuaranteeAmount//信保订单金额USD
        })


        form.render();
    }
    //附件
    function getfujian() {
        $.ajax({
            type : 'GET',
            //  url : 'resource/getTree',
            url:'shipmentPlan/selectFileBySpId',
            data:{"shipmentPlanId":id},
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    // productList=da.data;
                    // fujian.push(da.data);
                    fujian=da.data;
                }
            },
            error: function(data) {
                // layer.msg("获取失败!"); 日志
            }
        });
        table.reload('attachmenttableid',{data : fujian});
    }
    //产品获取数据
    function  getProdcuInfo() {

        $.ajax({
            type : 'GET',
            //  url : 'resource/getTree',
            url:'shipmentPlan/selectProductByShipmentPlanId',
            data:{"spId":id},
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    // productList=da.data;
                    getProductList(da.data);
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
    }
    //费用 获取数据
    function getfeiyong() {
        $.ajax({
            type : 'GET',
            //  url : 'resource/getTree',
            url:'shipmentPlan/selectCostBySpId',
            data:{"shipmentPlanId":id},
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    // productList=da.data;
                    // feiyong.push(da.data);
                    feiyong=da.data;
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
        table.reload('costtableid',{data : feiyong});

    }
    //获取下拉列表值
    function getlxandlevel() {
        var curry=getdictionary(5,14);//币种
        var termspay=getdictionary(5,18);//收款方式
        var priceterm=getdictionary(5,16);//价格术语
        var business=getdictionary(6,20);//业务模式
        var destin = getdictionary(6,29) //目的地
        var places = getdictionary(6,31); //起运地
        var bankValue = getdictionary(6,32); //银行
        var unit = getdictionary(6,42); //单位
        var costtype = getdictionary(5,19);  //费用类型
        var declarecompany=getdictionary(6,48);//报关抬头
        var transmode=getdictionary(2,5);//运输方式
        var stock=getdictionary(4,11);//仓库

        var currency=$("select[name='currency']");//币种
        var priceterms = $("select[name='priceTerm']"); //价格术语
        var termspayment = $("select[name='paymentTerm']"); //收款类型
        var businessmode = $("select[name='businessMode']"); //业务模式
        var place = $("select[name='startPlace']"); //起运地
        var destination = $("select[name='endPlace']"); //目的地
        var bank = $("select[name='bankCode']"); //银行
        var declarecompanystr=$("select[name='declareCompany']");//报关抬头
        var transmodestr=$("select[name='transMode']");//运输方式
        var targetcountrystr=$("select[name='targetCountry']");//运抵国家
        var stockstr=$("select[name='stock']");//仓库
        var unitselect = $("select[name='unitselect']"); //单位
        var costtypeselect = $("select[name='costtypeselect']");   //费用类型

        currency.append(getoption(curry)); //币种
        priceterms.append(getoption(priceterm)); //价格术语
        termspayment.append(getoption(termspay)); //付款方式
        businessmode.append(getoption(business)); //业务模式
        place.append(getoption(places)); //起运地
        destination.append(getoption(destin)); //目的地
        bank.append(getoption(bankValue)); //银行
        unitselect.append(getoption(unit)); //单位
        costtypeselect.append(getoption(costtype));    //费用类型
        declarecompanystr.append(getoption(declarecompany));//报关抬头
        transmodestr.append(getoption(transmode));//运输方式
        targetcountrystr.append(getoption(destin));//运抵国家
        stockstr.append(getoption(stock));//运抵国家

        form.render();

    }

    function setPullMenu(){
        var company = getCompany();   //签约公司
       // var customer = getCustomer();   //客户名称
        var opname=getUser();//业务员
        var companyid = $("select[name='companyCode']"); //签约公司
        var customername = $("select[name='customerCode']"); //客户名称
        var opnamestr=$("select[name='salesmanCode']"); //业务员


        companyid.append(getoption(company));
       // customername.append(getoption(customer));
        opnamestr.append(getoption(opname));
        form.render();
    }

    //获取签约公司
    function getCompany() {
        var obj=[];
        $.ajax({
            type : 'GET',
            //  url : 'resource/getTree',
            url:'shipmentPlan/getCompany',
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){

                    for(var i=0;i<da.data.length;i++){
                        var data={};
                        data.code=da.data[i].code;
                        data.name=da.data[i].name;
                        obj.push(data);
                    }
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
        return obj;
    }
    //获取客户
    function getCustomer() {
        var obj=[];
        $.ajax({
            type : 'GET',
            //  url : 'resource/getTree',
            url:'shipmentPlan/getCustomer',
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    // obj=da.data;
                    for(var i=0;i<da.data.length;i++){
                        var data={};
                        data.code=da.data[i].code;
                        data.name=da.data[i].name;
                        obj.push(data);
                    }
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
        return obj;
    }

    //获取用户
    function getUser() {
        var obj=[];
        $.ajax({
            type : 'GET',
            //  url : 'resource/getTree',
            url:'shipmentPlan/getAllUser',
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    for(var i=0;i<da.data.length;i++){
                        var data={};
                        data.code=da.data[i].code;
                        data.name=da.data[i].name;
                        obj.push(data);
                    }
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
        return obj;
    }
    function  getoption(objs) {
        var stoptions="";
        for(var i=0;i<objs.length;i++){
            stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
        }
        return stoptions;
    }

    //回显时拼装产品列表与部件列表
    function getProductList(data) { 
        var changeList=[];
        for(var i=0;i<data.length;i++){
            // data[i].supplierName=data[i].supplierCode;
            if(data[i].type=="1") {//产品
                productList.push(data[i]);
            }else{//部件
                changeList.push(data[i]);
            }
        }
        //遍历changeList，组装部件列表
        for(var i=0;i<changeList.length;i++){
            var productId=changeList[i].productId;
            getPeijianList(productId,changeList[i]);
        }

        /*  var jsons = {"productId":data[i].productId,"changeList":changeList};
          peijianList.push(jsons);*/
    }
    //组装部件列表
    function getPeijianList(productId,pj) {
        var tf=false;
        for(var i=0;i<peijianList.length;i++){
            if(productId == peijianList[i].productId){
                tf=true;
                (peijianList[i].changeList).push(pj);
                break;
            }
        }
        if(! tf){
            var changeList=[];
            changeList.push(pj);
            var jsons = {"productId":productId,"changeList":changeList};
            peijianList.push(jsons)
        }

    }

    //获取货柜型号
    function getContainerModel(){

        $.ajax({
            url:"offer/getContainerModel",
            async:false,
            success:function(data){
                if(data.status == 200){
                    containerModel = data.data;
                    for(let i in data.data){
                        $('#containerTypeCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });
    }
    //判断当前登录用户是否为 营销部门的总监 角色
    function is_marketing_director() {
        $.ajax({
            url:'customer/isMarketingDirector',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    isMarketingDirector=da.data;
                }
            }
        });
    }
    function getIsContainsRoleShipPlan(){
        $.ajax({
            url: 'shipmentPlan/isContainsRoleShipPlan',
            async: false, // 同步
            success: function (data) {
                if (data.status==200){
                    isContainsRoleShipPlan=data.data;
                }
            }
        });
    }